<template>
  <div class="article-container">
    <el-card class="article-card">
      <template #header>
        <div class="card-header">
          <span>文章管理</span>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>发表文章
          </el-button>
        </div>
      </template>
      
      <!-- 搜索区域 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item>
          <el-input 
            v-model="searchForm.title" 
            placeholder="请输入文章标题" 
            clearable
            style="width: 300px;"
          />
        </el-form-item>
        <el-form-item>
          <el-select 
            v-model="searchForm.categoryName" 
            placeholder="请选择文章分类" 
            clearable
            style="width: 200px;"
          >
            <el-option
              v-for="item in categories"
              :key="item.categoryName"
              :label="item.categoryName"
              :value="item.categoryName"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select 
            v-model="searchForm.state" 
            placeholder="请选择发布状态" 
            clearable
            style="width: 200px;"
          >
            <el-option label="发布" value="发布" />
            <el-option label="草稿" value="草稿" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 文章列表 -->
      <el-table :data="articles" style="width: 100%" v-loading="loading">
        <el-table-column prop="title" label="标题" />
        <el-table-column prop="categoryName" label="分类" width="100" />
        <el-table-column prop="state" label="状态" width="100" />
        <el-table-column prop="updateTime" label="更新时间" width="180" />
        <el-table-column fixed="right" label="操作" width="180">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">
              <el-icon><Edit /></el-icon>编辑
            </el-button>
            <el-button type="danger" link @click="handleDelete(row)">
              <el-icon><Delete /></el-icon>删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="page"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 发表文章对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '发表文章' : '编辑文章'"
      width="80%"
      @close="handleClose"
    >
      <el-form
        ref="formRef"
        :model="articleForm"
        :rules="articleRules"
        label-width="100px"
      >
        <el-form-item label="文章标题" prop="title">
          <el-input v-model="articleForm.title" placeholder="请输入文章标题" />
        </el-form-item>
        <el-form-item label="文章分类" prop="categoryName">
          <el-select v-model="articleForm.categoryName" placeholder="请选择文章分类" style="width: 100%;">
            <el-option
              v-for="item in categories"
              :key="item.categoryName"
              :label="item.categoryName"
              :value="item.categoryName"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="封面图片" prop="coverImg">
          <el-upload
            class="cover-uploader"
            :show-file-list="false"
            :before-upload="beforeCoverUpload"
            :http-request="uploadCover"
          >
            <img v-if="articleForm.coverImg" :src="articleForm.coverImg" class="cover" />
            <el-icon v-else class="cover-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">选填，支持jpg、png、gif格式，大小不超过2MB</div>
        </el-form-item>
        <el-form-item label="文章内容" prop="content">
          <div class="editor-container">
            <el-input
              v-model="articleForm.content"
              type="textarea"
              :rows="8"
              placeholder="请输入文章内容"
              resize="none"
            />
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="info" @click="handleSave('草稿')">存为草稿</el-button>
          <el-button type="primary" @click="handleSave('发布')">发 布</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Plus, Edit, Delete, Search, Refresh } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '../utils/request'

// 搜索表单
const searchForm = reactive({
  title: '',
  categoryName: '',
  state: ''
})

// 分页参数
const page = ref(1)
const pageSize = ref(10)
const total = ref(0)
const loading = ref(false)

// 文章列表
const articles = ref([])
// 分类列表
const categories = ref([])

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)

// 文章表单
const articleForm = reactive({
  title: '',
  content: '',
  coverImg: '',
  categoryName: '',
  state: ''
})

// 表单验证规则
const articleRules = {
  title: [
    { required: true, message: '请输入文章标题', trigger: 'blur' },
    { min: 1, max: 30, message: '标题长度应在1-30个字符之间', trigger: 'blur' }
  ],
  categoryName: [
    { required: true, message: '请选择文章分类', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入文章内容', trigger: 'blur' }
  ]
}

// 获取文章列表
const getArticles = async () => {
  loading.value = true
  try {
    const res = await request.get('/article/page', {
      params: {
        page: page.value,
        pageSize: pageSize.value,
        title: searchForm.title || undefined,
        categoryName: searchForm.categoryName || undefined,
        state: searchForm.state || undefined
      }
    })
    if (res.code === 200) {
      articles.value = res.data.records || []
      total.value = res.data.total || 0
    } else {
      ElMessage.error(res.msg || '获取文章列表失败')
    }
  } catch (error) {
    console.error('获取文章列表失败:', error)
    ElMessage.error('获取文章列表失败')
  } finally {
    loading.value = false
  }
}

// 获取分类列表
const getCategories = async () => {
  try {
    const res = await request.get('/category/list')
    if (res.code === 200) {
      categories.value = res.data || []
    } else {
      ElMessage.error(res.msg || '获取分类列表失败')
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
    ElMessage.error('获取分类列表失败')
  }
}

// 搜索
const handleSearch = () => {
  page.value = 1
  getArticles()
}

// 重置
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  page.value = 1
  pageSize.value = 10
  getArticles()
}

// 分页大小改变
const handleSizeChange = (val) => {
  pageSize.value = val
  getArticles()
}

// 页码改变
const handleCurrentChange = (val) => {
  page.value = val
  getArticles()
}

// 新增文章
const handleAdd = () => {
  dialogType.value = 'add'
  articleForm.title = ''
  articleForm.content = ''
  articleForm.coverImg = ''
  articleForm.categoryName = ''
  articleForm.state = ''
  dialogVisible.value = true
}

// 编辑文章
const handleEdit = (row) => {
  dialogType.value = 'edit'
  // 填充表单数据
  articleForm.title = row.title
  articleForm.content = row.content || ''
  articleForm.coverImg = row.coverImg || ''
  articleForm.categoryName = row.categoryName
  articleForm.state = row.state
  dialogVisible.value = true
}

// 删除文章
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确认删除该文章吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const res = await request.delete(`/article/delete/${row.id}`)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      getArticles()
    } else {
      ElMessage.error(res.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除文章失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 上传封面图片前的处理
const beforeCoverUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('封面图片只能是图片格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('封面图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 上传封面图片
const uploadCover = async (options) => {
  try {
    const formData = new FormData()
    formData.append('file', options.file)
    const res = await request.post('/upload', formData)
    if (res.code === 200) {
      articleForm.coverImg = res.data
      ElMessage.success('封面上传成功')
    } else {
      ElMessage.error(res.msg || '封面上传失败')
    }
  } catch (error) {
    console.error('封面上传失败:', error)
    ElMessage.error('封面上传失败')
  }
}

// 保存文章
const handleSave = async (state) => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        articleForm.state = state
        const res = await request({
          method: dialogType.value === 'add' ? 'PUT' : 'PATCH',
          url: dialogType.value === 'add' ? '/article/add' : '/article/update',
          data: articleForm
        })
        if (res.code === 200) {
          ElMessage.success(
            dialogType.value === 'add' 
              ? (state === '发布' ? '文章发布成功' : '文章已保存为草稿')
              : '文章修改成功'
          )
          dialogVisible.value = false
          getArticles() // 刷新文章列表
        } else {
          ElMessage.error(res.msg || '保存失败')
        }
      } catch (error) {
        console.error('保存文章失败:', error)
        ElMessage.error('保存失败')
      }
    }
  })
}

// 关闭对话框时重置表单
const handleClose = () => {
  formRef.value?.resetFields()
  articleForm.title = ''
  articleForm.content = ''
  articleForm.coverImg = ''
  articleForm.categoryName = ''
  articleForm.state = ''
  dialogVisible.value = false
}

onMounted(() => {
  getArticles()
  getCategories()
})
</script>

<style scoped>
.article-container {
  min-height: 100%;
}

.article-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-form--inline .el-form-item) {
  margin-right: 16px;
}

.cover-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
}

.cover-uploader:hover {
  border-color: var(--el-color-primary);
}

.cover-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  line-height: 178px;
}

.cover {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
}

.editor-container {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  margin-bottom: 20px;
  width: 100%;
}

.editor-container :deep(.el-textarea__inner) {
  border: none;
  padding: 10px 15px;
  height: 120px !important;
  font-size: 14px;
  line-height: 1.6;
  width: 100%;
  box-sizing: border-box;
}

.upload-tip {
  font-size: 12px;
  color: #999;
  margin-top: 8px;
}

.el-dialog {
  --el-dialog-width: 90%;
}
</style> 